class Solution:
    # 压缩矩阵
    def convert(self, s: str, numRows: int) -> str:
        n = len(s)
        if n <= numRows:
            return s
        if numRows == 1:
            return s
        if numRows == 2:
            one, two = "", ""
            for i in range(n):
                if i % 2 == 0:
                    one += s[i]
                else:
                    two += s[i]
            return one + two
        
        strings = []
        i, col = 0, 1
        lastCol = ""  # 对最后一列特殊处理
        while i <= n-1:
            if col % 2 == 1:  # 完全列
                if i+numRows >= n:
                    lastCol = s[i:] + " "*(numRows-len(s[i:]))  # 补位
                    break
                strings.append(s[i:i+numRows])
                i += numRows
                col += 1
            else:  # 斜边
                next = i+numRows-2
                if next >= n:
                    n_last = len(s[i:])
                    lastCol = " "*(numRows-1-n_last) + self.reverse(s[i:]) + " "
                    break
                rev = s[i:next]
                if rev != "":
                    strings.append(" "+self.reverse(rev)+" ")  # 补位
                    col += 1
                i = next
        
        # 此时 lastCol 必不为空
        res = ""
        for i in range(numRows):
            for j in range(len(strings)):
                if strings[j][i] != " ":
                    res += strings[j][i]
            if lastCol[i] != " ":
                res += lastCol[i]
        return res
    
    def reverse(self, string: str) -> str:
        ret = ""
        for c in string:
            ret = c + ret
        return ret
